<template>
  <el-card>
    <template #header> 修改密码 </template>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="密码" prop="pass">
        <el-input
          type="password"
          v-model="ruleForm.pass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPass">
        <el-input
          type="password"
          v-model="ruleForm.newPass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input v-model="ruleForm.checkPass"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { api_users_checkoldpwd, api_users_editpwd } from "@/api/user";
export default {
  data() {
    let oldPass = async (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (!/^\d{6,12}$/.test(value)) {
        callback(new Error("请输入正确的密码格式"));
      } else {
        let res = await api_users_checkoldpwd({ oldPwd: value });
        let { code, msg } = res.data;
        if (code === 200) {
          callback();
        }
      }
    };
    let newPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (!/^\d{6,12}$/.test(value)) {
        callback(new Error("请输入正确的密码格式"));
      } else if (value === this.ruleForm.pass) {
        callback(new Error("新密码不能和旧密码一致"));
      } else {
        callback();
      }
    };
    let checkPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (value !== this.ruleForm.newPass) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: "",
        checkPass: "",
        newPass: "",
      },
      rules: {
        pass: [{ validator: oldPass, trigger: "blur" }],
        newPass: [{ validator: newPass, trigger: "blur" }],
        checkPass: [{ validator: checkPass, trigger: "blur" }],
      },
    };
  },
  methods: {
    submit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await api_users_editpwd({
            newPwd: this.ruleForm.newPass,
          });
          let { code, msg } = res.data;
          if (code === 0) {
            this.$router.push("/login");
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  width: 300px;
}
</style>